import os
import configparser
from common.log import Log
from common.utils import MyDict
from conf import config
import yaml



class InIConfig:

    @classmethod
    def get_config_form_ini(cls, file_name):
        if not os.path.isfile(file_name):  # 判断文件是否存在，不存报错
            raise FileNotFoundError

        c = configparser.ConfigParser()  # 实例化解析类
        c.read(file_name)  # 读取文件
        all_node = MyDict()
        for node in c.sections():
            all_node[node] = MyDict(c[node])
        return all_node

    @classmethod
    def get_node(cls, node, ini_file=config.ini_config_file):
        abs_path = os.path.join(config.config_path, ini_file)
        all_node = cls.get_config_form_ini(abs_path)
        return all_node.get(node)


class YamlConfig:

    @classmethod
    def get_config_form_yaml(cls, file_name):
        if not os.path.isfile(file_name):  # 判断文件是否存在，不存报错
            raise FileNotFoundError
        with open(file_name, encoding="utf-8") as fr:
            try:
                ret = yaml.load(fr, yaml.SafeLoader)
            except:
                Log.error("{}文件解析出错，格式不正确", file_name)
                return {}
            else:
                return ret

    @classmethod
    def get_rainbow_config(cls, node=None):
        abs_path = os.path.join(config.config_path, config.yaml_config_file)
        config_info = cls.get_config_form_yaml(abs_path)
        return config_info.get(node)
        # if node:
        #     return config_info.get(node)
        # return config_info
    # def get_rainbow_config(cls, node,yaml_file=config.yaml_config_file):
    #     abs_path = os.path.join(config.config_path, yaml_file)
    #     config_info = cls.get_config_form_yaml(abs_path)
    #     if node in config_info:
    #         return config_info.get(node)
    #     return config_info

if __name__ == '__main__':
    print(YamlConfig.get_rainbow_config())
    print(YamlConfig.get_rainbow_config("email"))
    print(YamlConfig.get_rainbow_config("email1"))


'''
因为conf>config.py中写了这样一行代码：
cur_env = YamlConfig.get_rainbow_config("default_env")
报错，变成死循环：
Traceback (most recent call last):
  File "D:/PythonProject/pythonProject2/day11/rainbow/common/config_parse.py", line 3, in <module>
    from common.log import Log
  File "D:\PythonProject\pythonProject2\day11\rainbow\common\log.py", line 2, in <module>
    from conf import config
  File "D:\PythonProject\pythonProject2\day11\rainbow\conf\config.py", line 2, in <module>
    from common.config_parse import YamlConfig
  File "D:\PythonProject\pythonProject2\day11\rainbow\common\config_parse.py", line 3, in <module>
    from common.log import Log
ImportError: cannot import name 'Log'

解决办法：
从conf>config.py中，把下面这些信息拿出来，放到common>const.py中
from common.config_parse import YamlConfig
cur_env = YamlConfig.get_rainbow_config("default_env")
'''